<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>投票</title>
    <meta name="description" content="投票" />
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
    <meta name="format-detection" content="telephone=no">
    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" type="text/css" href="css/default.css" />
    <link rel="stylesheet" type="text/css" href="css/component.css" />
    <link rel="stylesheet" href="./css/frozen.css">
    <link rel="stylesheet" href="./css/vote.css">
    <link rel="stylesheet" href="../common/css/plugins.css" media="screen" title="no_title" charset="utf-8">
    <script src="js/modernizr.custom.js"></script>
    <script src="js/jquery.min.js"></script>
    <style>
        .detailHeader .resource{
            display: block;
            width: 100%;
            margin-top: 10px;
            position: relative;
        }
        .detailHeader .resource img,.detailHeader .resource video,.detailHeader .resource audio{
            width: 100%;
            display: block;
            vertical-align: middle;
        }
        img,video,audio{
            max-width: 100%;
            display: block;
            vertical-align: middle;
            margin-top: 5px;
        }
        .detailHeader .resource video{
            height: 7.6rem;
        }
        .detailHeader .resource audio{
            position: absolute;
            bottom: 0;
        }
        .rule p{
            word-break: break-all;
        }
        .layui-m-layer0 .layui-m-layerchild{
            background-color: #e5cb86 !important;
        }
        .layui-m-layerbtn{
            background-color: #e5cb98 !important;
        }
        .layui-m-layerbtn span[yes] {
            color: #901d1d !important;
        }

        .layui-m-layerbtn span[no] {
            color: #901d1d !important;
        }
        .layui-m-layercont {
            color: #901d1d !important;
        }
        .main{
            padding: 10px;
        }
    </style>
</head>
<body>
<div id="mainWrap"></div>
<script src="js/artTemplate/artTemplate.js"></script>
<script src='js/vote-tpl.js'></script>
<script src="js/layer/layer.js"></script>
<script src="js/masonry.pkgd.min.js "></script>
<script src="js/imagesloaded.js "></script>
<script src="js/classie.js "></script>
<script src="js/AnimOnScroll.js "></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="../common/js/weixinshare.js"></script>
<script>
    function QRCode(qrcode){
        var $mask = $('<div class="mask-layer">' +
            '             <div class="cover"></div>' +
            '             <div class="content">'+
//            '                 <div class="close icon"></div>' +
            '                 <div class="qr-code"></div>' +
            '                 <div class="slogan">扫描二维码,关注公众号后参与活动</div>' +
            '             </div>' +
            '         </div>');
        $mask.find('.close.icon').click(function(e){
            $mask.remove();
        });

        return {
            open: function(){
                if(qrcode){
                    $mask.find('.qr-code').html('<img src="'+qrcode+'" alt="二维码"/>');
                }
                $('body').append($mask);
            },
            close: function(){
                $mask.remove();
            }
        }
    }
    function forbidShare() {
        function onBridgeReady() {
            WeixinJSBridge.call('hideOptionMenu');
        }

        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }
    }
</script>
<script>
    window.addEventListener("popstate",function(e){
        window.location=window.location.href;
    })
    var isWechat = false,isAPP = false,isFollow = false,isCode=false,isPart=false,activities={},vote_token='';
    var url = '/',act_info='';
    window.parameter = GetRequest(window.location.href);
    window.commonData = {
        pagination : {  page : 0,//当前页码
            per_page : 10//每页请求多少条数据
        },
        paginationRank : {  page : 0,//当前页码
            per_page : 10//每页请求多少条数据
        },
        index : 0
    };
    /*
     * 获取?后面的参数并返回 json 对象
     */
    function GetRequest(url) {
        if (!url || url.indexOf('?') == -1) {
            return {};
        }
        var url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
        var theRequest = new Object();
        var str = decodeURI(url);
        var strs;
        if (str.indexOf("&") != -1) {
            strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        } else {
            theRequest[str.split("=")[0]] = unescape(str.split("=")[1]);
        }
        return theRequest;
    }


    function bindEvent() {
        //IOS中激活a标签active事件
        var a = document.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            a[i].addEventListener('touchstart', function() {}, false);
        }
        document.body.addEventListener('touchstart', function() {});

        $('#mainWrap').on('click', '.voteTab li', function() {
            var index = $(this).index();
            commonData.index = index;
            $(this).addClass('cur').siblings('li').removeClass('cur');
            $('.tabList').hide().eq(index).show();
            new AnimOnScroll(document.getElementById('grid_'+commonData.index), {
                minDuration: 0.4,
                maxDuration: 0.7,
                viewportFactor: 0.2
            });
            if (index == 2) {
                layer.open({
                    type: 2,
                    shadeClose: false
                });
                window.commonData.paginationRank.page = 0;
                rankDateCallBack();
            }
        })
        $('body').on('click', '.closeItem', function() {
            layer.closeAll();
        })

        //列表投票按钮触发事件
        $('#mainWrap').on('click', '.voteBtnItem', function() {
            layer.open({
                type: 2,
                shadeClose: false
            });
            var type = $(this).attr('voteType');
            var vId = $(this).attr('voteId');
            itemCallBack(vId, type);
        })

        //搜索按钮
        $('#mainWrap').on('click', '#searchBtn', function() {
            var query = $.trim($(this).prev('input').val());
            if(!query){
                layer.open({
                    className: 'messageStyle',
                    content: '搜索关键词不能为空'
                });
            }else{
                layer.open({
                    type: 2,
                    shadeClose: false
                });
                searchCallBack($(this).prev('input').val());
            }
        })

        //投票按钮
        $('body').on('click', '.voteBtn', function() {
            if (!isPart&&!window.parameter.uid && !window.parameter.mfSign) {
                if (activities.publishing.app.app_urls[0]) {
                    layer.open({
                        content: '请下载APP参与投票'
                        , btn: ['确定', '取消']
                        , yes: function (index) {
                            location.href = activities.publishing.app.app_urls[0];
                            layer.close(index);
                        }
                    });
                } else {
                    layer.open({
                        content: '请下载APP参与投票'
                        , btn: '确定'
                    });
                }
                return;
            }
            if (!isPart&&!window.parameter.uid && window.parameter.mfSign) {
                var paramJson = GetRequest(window.location.href);
                var param = '';
                //有noLogin参数
                if (window.location.search.indexOf('noLogin') != -1) {
                    $.each(paramJson, function(val, i) {
                        if (val != 'noLogin') {
                            param += val + '=' + paramJson[val] + '&'
                        }
                    })
                    param = param.slice(0, -1);
                    window.location.href = window.location.origin + window.location.pathname + '?' + param + '&noLogin=true';
                } else { //没noLogin参数
                    window.location.href = window.location.origin + window.location.pathname + window.location.search + '&noLogin=true';
                }
                return;
            }

            var item_id = $(this).attr('voteId');
            var uid = window.parameter.uid;
            voteCallBack(item_id, uid);
            return false;
        })
    }




    /**
     * 验证sign
     */
    function signCallBack() {
//        layer.open({
//            type: 2,
//            shadeClose: false
//        });
        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data: window.parameter,
            type: 'get',
            success: function(ajaxData) {
                if (ajaxData.code == '200') {
                    vote_token = ajaxData.vote_token;
                    listDateCallBack();
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                }
            }
        })
    }
    function noUpdateSignCallBack() {
        var data = {};
        for (x in window.parameter) {
            if(x == 'vote_id'){
                continue;
            }
            data[x] = window.parameter[x]
        }

        $.ajax({
            url: url + 'api/app/sign/mf.php',
            data: data,
            type: 'get',
            success: function (ajaxData) {
                if (ajaxData.code == '200') {
                    vote_token = ajaxData.vote_token;
                } else {
                    layer.open({
                        className: 'messageStyle'
                        , content: ajaxData.message
                    });
                }
            }
        })
    }

    if(window.parameter['ways']!='wechat'){
        //没有uid 和 userid 不验签
        if (!window.parameter.userid && !window.parameter.uid) {
            listDateCallBack();
        } else {
            signCallBack();
        }
    }else{
        isSignPass = 1;
        vote_token = window.parameter['vote_token'];
        listDateCallBack();
    }
    function jugdeSignPass(){
        if(window.parameter['ways']!='wechat'&&(window.parameter.userid||window.parameter.uid)){
            noUpdateSignCallBack();
        }
    }

    /**
     * 获取投票列表数据
     * @return  {[type]}  [description]
     */
    function listDateCallBack() {
        $.ajax({
            url: url + 'lua/api/poll/summary',
            data: {
                act_id: window.parameter.act_id
            },
            type: 'get',
            success: function(ajaxData) {
                if (ajaxData.code == '200') {
                    act_info = ajaxData.data;
                    //供详情等页面用
                    commonData.data = ajaxData.data;
                    data = ajaxData.data;
                    var tplHTML = voteTpl.mainHtml({
                        data: data
                    });
                    $('#mainWrap').html(tplHTML);
                    listItemCallBack();
                    bindEvent();
                    setTimeout(function(){
                        $('.copyright').show();
                        if( browser.versions.iPhone){
                            $('body').append('<p class="center copyright">活动所有奖品与苹果公司无关</p>');
                        }
                    },1000)
                    //===============================
                    activities = ajaxData.data;
                    isWechat = (window.parameter.ways == 'wechat');//是否开启微信
                    isAPP = (activities.publishing.app.is_open =='on');//是否开启APP
                    isFollow = (window.parameter['following']!=1);//是否关注
                    isCode = Boolean(activities.publishing.wechat.qr_code[0]);//是否上传二维码
                    if(isWechat){
                        if(isFollow){
                            isPart = true;
                        }else{
                            if(isCode){
                                var qrCode = QRCode(activities.publishing.wechat.qr_code[0]).open();
                            }else{
                                isPart = true;
                            }
                        }
                    }else{
                        //APP
                    }
                    if (typeof wxshare != 'undefined' && (activities.shares.isopen == 'on' || activities.shares.isopen == '1')) {
                        var shareLink = '';
                        if(isWechat){
                            shareLink =window.location.origin+'/wechat/shares?id='+window.parameter.act_id;
                        }else{
                            shareLink = window.location.origin + location.pathname + '?act_id=' + wxshare.getUrlParam('act_id');
                        }
                        wxshare.share({
                            title: activities.shares.title,
                            desc: activities.shares.content,
                            link: shareLink,
                            imgUrl: activities.shares.thumb,
                        });
                    }else{
                        forbidShare();
                    }
                    //===========================
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message,
                    });
                }
            }
        })
    }
    //listDateCallBack();

    /**
     * 获取无限加载列表页面
     * @return  {[type]}  [description]
     */
    function listItemCallBack(){
        ++window.commonData.pagination.page;
        $.ajax({
            url: url + 'lua/api/poll/items',
            data: {
                act_id: window.parameter.act_id,
                per_page:window.commonData.pagination.per_page,
                page:window.commonData.pagination.page
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    var tplHTML = voteTpl.list({
                        data: ajaxData.data
                    });
                    $('#grid_'+commonData.index).append(tplHTML);
                    new AnimOnScroll(document.getElementById('grid_'+commonData.index), {
                        minDuration: 0.4,
                        maxDuration: 0.7,
                        viewportFactor: 0.2
                    });
                    if(ajaxData.data.items.length < window.commonData.pagination.per_page){
                        loading = true;
                        $('#loading').html('没有更多数据');
                    }else{
                        loading = false;
                    }

                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                }
            }
        })
    }
    /**
     * 获取排名列表数据
     * @return  {[type]}  [description]
     */
    function rankDateCallBack() {
        ++window.commonData.paginationRank.page;
        $.ajax({
            url: url + 'lua/api/poll/rank',
            data: {
                act_id: window.parameter.act_id,
                per_page:window.commonData.paginationRank.per_page,
                page:window.commonData.paginationRank.page
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    var tplHTML = voteTpl.rank({
                        data: ajaxData.data
                    });
                    $('#grid_'+commonData.index).html(tplHTML);
                    new AnimOnScroll(document.getElementById('grid_'+commonData.index), {
                        minDuration: 0.4,
                        maxDuration: 0.7,
                        viewportFactor: 0.2
                    });
                    if(ajaxData.data.items.length < window.commonData.pagination.per_page){
                        loading = true;
                        $('#loading').html('没有更多数据');
                    }else{
                        loading = false;
                    }
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * item_id : 候选项的id
     * type : 详情类型 1 图片 2 音频 3 视频 4 外链
     */
    function itemCallBack(item_id, type) {
        $.ajax({
            url: url + 'lua/api/poll/item',
            data: {
                'act_id': window.parameter.act_id,
                'item_id': item_id,
                'uid':window.parameter.uid
            },
            type: 'get',
            success: function(ajaxData) {
                layer.closeAll();
                if (ajaxData.code == '200') {
                    window.history.pushState("", "poll", window.location.search);
                    layer.open({
                        type: 1,
                        content: '<div style="background-color:#fff;height:' + $(window).height() + 'px"><i class="closeItem" ></i>' + voteTpl['items' + type]({
                            data: {
                                data: ajaxData.data,
                                commonData: window.commonData.data
                            }
                        }) + '</div>',
                        style: 'position:absolute; bottom:0; left:0; width: 100%; height:100%; padding:0; border:none;    overflow: auto;'
                    });
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                }
            }
        })
    }

    /**
     * 投票详情
     * `q`: 关键字 （只能完全匹配）
     */
    function searchCallBack(q) {
        $.ajax({
            url: '/api/vote/'+window.parameter.act_id+'/search',
            data: {
                'q': q
            },
            type: 'get',
            success: function(data) {
                if(data.code==200){
                    var obj = {
                        'act_id': window.parameter.act_id,
                        'ids': data.data.ids
                    };
                    $.ajax({
                        url: url + 'lua/api/poll/search',
                        data:  JSON.stringify(obj),
                        type: 'POST',
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        success: function(ajaxData) {
                            layer.closeAll();
                            if (ajaxData.code == 200){
                                var tplHTML = voteTpl.search({
                                    data: ajaxData.data
                                });
                                console.log(ajaxData.data);
                                $('#grid_'+commonData.index).html(tplHTML);
                                new AnimOnScroll(document.getElementById('grid_'+commonData.index), {
                                    minDuration: 0.4,
                                    maxDuration: 0.7,
                                    viewportFactor: 0.2
                                });
                            } else {
                                $('.searchBox').html('<p class="noResults">' + ajaxData.message + '</p>');
                            }
                        }
                    })
                }else{
                    layer.open({
                        className: 'messageStyle',
                        content: data.message
                    });
                }
            }
        })
    }
    /**
     * 投票
     *  `item_id`: 候选项的id
     *  `uid`: 用户id
     */
    function voteCallBack(item_id, uid) {
        var index = layer.open({
            type: 2,
            shadeClose: false
        });
        var params = {
            act_id: window.parameter.act_id,
            item_id: item_id,
            uid: uid,
            vote_token: vote_token
        };
        var postData = $.extend({},window.parameter,params);
        $.ajax({
            url: url + 'lua/api/poll/vote',
            data: postData,
            type: 'get',
            success: function(ajaxData) {
                layer.close(index);
                if (ajaxData.code == 200) {
                    $('#vote1_' + item_id).html(parseInt($('#vote1_' + item_id).html()) + 1);
                    $('#vote_' + item_id).html(parseInt($('#vote_' + item_id).html()) + 1);
                    layer.open({
                        time: 1,
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                } else {
                    layer.open({
                        className: 'messageStyle',
                        content: ajaxData.message
                    });
                }
                jugdeSignPass();
            }
        })
    }

    var loading = false;//避免重复加载

    $(window).scroll(function() {
        if (loading) {
            return;
        }
        var scrollTop = $(document).scrollTop();
        var Hdocument = $(document).height(); //是获取整个页面的高度
        var Hwindow = $(window).height();

        if (Hdocument * .7 < Hwindow + scrollTop) {
            loading = true;
            listItemCallBack();
        }
    })

    var browser={
        versions:function(){
            var u = navigator.userAgent, app = navigator.appVersion;
            return {         //移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin : u.toLowerCase().match(/MicroMessenger/i) == "micromessenger" ? true : false//判断是否为微信
            };
        }(),
        language:(navigator.browserLanguage || navigator.language).toLowerCase()
    }

</script>
</body>

</html>
